package com.mt.lulucai.usbdriver.help;

import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.mt.lulucai.bean.ReciveMsg;
import com.mt.lulucai.util.netty.NettyClient;

import java.io.IOException;
import java.net.Socket;
import java.nio.ByteBuffer;

public class GlobalVariable {


	private static final int BUFSIZ = 4096;
	private static GlobalVariable mGlobalVariable;
	private final ByteBuffer mReadBuffer = ByteBuffer.allocate(BUFSIZ);
	public static UsbSerialPort sPort;
	public static StringBuffer sb = new StringBuffer();


	private boolean isOpen;
	private int timeOut = 5000;
	private final HexUtil mHexUtil = new HexUtil();

	private NettyClient nettyClient;//socket操作连接对象

	public static GlobalVariable getinstance() {
		if (mGlobalVariable == null) {
			mGlobalVariable = new GlobalVariable();
		}
		return mGlobalVariable;
	}

	private GlobalVariable() {

	}

	public boolean isOpen() {
		return isOpen;
	}

	public void setOpen(boolean open) {
		isOpen = open;
	}

	/**
	 * usb通讯，发送数据
	 * @param sendMsg
	 */
	public void sendMsg(String sendMsg) throws IOException {
		//发送数据
		sendMsg.replaceAll(" ","");
		byte[] reallocates = mHexUtil.hexStringToBytes(sendMsg.toString());
		sPort.write(reallocates,timeOut);
	}


	/**
	 * 读取蓝牙信息
	 * @return
	 */
	public String readMsg() throws IOException {
		int length = sPort.read(mReadBuffer.array(),timeOut);
		if (length > 0) {
			final byte[] data = new byte[length];
			mReadBuffer.get(data, 0, length);
			mReadBuffer.clear();
			return mHexUtil.bytesToHexString(data).toUpperCase();
		}else{
			return null;
		}
	}

	public NettyClient getNettyClient() {
		return nettyClient;
	}

	public void setNettyClient(NettyClient nettyClient) {
		this.nettyClient = nettyClient;
	}

	/**
	 * usb通讯 读取信息
	 * @param reciveMsg
	 * @param callBack
	 */
	public void readMsg(String reciveMsg, ICallBack callBack){
		synchronized (this) {
			reciveMsg = reciveMsg.replaceAll(" ","");
			sb.append(reciveMsg);
			while (sb.length()>0){
				if (sb.toString().contains("AAEE")) {
					sb.delete(0,sb.toString().indexOf("AAEE"));
					if(sb.length()>4){
						int length = Integer.parseInt(sb.toString().substring(4,8),16);
						if(sb.length()>=length*2){
							String readMsg = sb.toString().substring(0,length*2);
							sb.delete(0,length*2);
							ReciveMsg tReciveMsg = new ReciveMsg();
							tReciveMsg.setReciveHexDataString(readMsg);
							tReciveMsg.setReciveHexData(mHexUtil.hexStringToBytes(readMsg));
							tReciveMsg.setDataLen(length);
							tReciveMsg.setReciveDataString(new String(mHexUtil.hexStringToBytes(readMsg.substring(8))));
							if(callBack!=null){
								callBack.onReciveData(tReciveMsg);
							}
						}else{
							break;
						}
					}else{
						break;

					}
				}else {
					break;
				}
			}
		}
	}
}
